'use client';
import {Button, Input} from 'antd';
import hljs from 'highlight.js/lib/core';
import plaintext from 'highlight.js/lib/languages/plaintext';
import {Marked, marked} from 'marked';
import {markedHighlight} from 'marked-highlight';
import {useEffect, useState} from 'react';
import trpc from '@/utils/trpc';
import 'highlight.js/styles/monokai-sublime.css';


function HomeUI(props: {
    url: string;
    md: string;
    mode: number;
    content: string;
    pageContent: string;
    aiText: string;
    onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
    onClick: (e: React.MouseEvent<HTMLButtonElement>) => void;
    onSwitchMode: (e: React.ChangeEvent<HTMLSelectElement>) => void;
    onChangeUrl: (e: React.ChangeEvent<HTMLInputElement>) => void;
    onChangeFile: (e: React.ChangeEvent<HTMLInputElement>) => void;
}) {
    return (
        <>
            <select value={props.mode} onChange={props.onSwitchMode}>
                <option value="1">ai总结摘要</option>
                <option value="2">提取页面内容</option>
                <option value="3">总结页面内容</option>
                <option value="4">提炼页面大纲</option>
            </select>
            <h1 className='tw-bg-gray-600 tw-flex'>{props.mode}</h1>
            <input type="file" multiple onChange={props.onChangeFile} />
            {props.mode === 2 ? (
                <Input value={props.url} onChange={props.onChangeUrl} />
            ) : (
                <Input value={props.content} onChange={props.onChange} />
            )}
            <Button type='primary' onClick={props.onClick}>提交</Button>
            {props.mode === 1 ? (
                <div>{props.aiText}</div>
            ) : (
                <>
                    <pre>{props.md}</pre>
                    <div dangerouslySetInnerHTML={{__html: props.pageContent}} />
                </>
            )}
        </>
    );
}

function useHome(props: {url: string; content: string}) {
    const {url, content} = props;
    const [aiText, setAiText] = useState('');
    const [md, setMd] = useState('');
    const [pageContent, setPageContent] = useState('');

    async function summaryContent() {
        const options = {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({content})
        };
        const res = await fetch('/api/bot/summary-content/stream', options);
        const reader = res.body?.getReader();
        if (!reader) return;

        const decoder = new TextDecoder();
        let total = '';
        let {done, value: data} = await reader.read();
        while (!done) {
            try {
                const [_, txt] = decoder.decode(data).match(/result":"([^"]*)"*/) || [];
                txt && (total += txt);
                setAiText(total);
            } catch (err) {
                console.log(err);
            }
            ({done, value: data} = await reader.read());
        }
    }

    async function extractPage() {
        const data = await trpc.page.extractContents.query({url});
        setMd(data);

        hljs.registerLanguage('plaintext', plaintext);
        const markedIn = new Marked({
            pedantic: false,
            gfm: true,
            breaks: false,
            renderer: new marked.Renderer(),
            ...markedHighlight({
                langPrefix: 'hljs language-',
                highlight(code, lang, info) {
                    return hljs.highlightAuto(code).value;
                }
            })
        });
        const contentRes = await markedIn.parse(data);
        setPageContent(contentRes);
    }

    return {
        aiText,
        md,
        pageContent,
        extractPage,
        summaryContent
    };
}

export default function Home() {
    const [mode, setMode] = useState(1);
    const [content, setContent] = useState('');
    const [url, setUrl] = useState('');
    const {aiText, summaryContent, md, pageContent, extractPage} = useHome({content, url});

    async function handleClick() {
        switch (mode) {
        case 1:
            summaryContent();
            break;
        case 2:
            extractPage();
            break;
        default:
            break;
        }
    }

    async function handleChangeFile(e: React.ChangeEvent<HTMLInputElement>) {
        // 上传图片
        if (!e.target.files) return;
        const file = e.target.files[0];
        if (!file) return;
        // 图片上传
        let formData = new FormData();
        formData.append('file', file);
        try {
            const res = await fetch('/api/upload', {method: 'POST', body: formData});
            const {data} = await res.json();
            console.log('🚀 ~ file: page.tsx:143 ~ handleChangeFile ~ res:', data);
        } catch (err) {
            console.log(err);
        }
    }

    useEffect(() => {}, []);

    return (
        <HomeUI
            mode={mode}
            md={md}
            url={url}
            content={content}
            pageContent={pageContent}
            aiText={aiText}
            onChange={e => setContent(e.target.value)}
            onChangeUrl={e => setUrl(e.target.value)}
            onClick={handleClick}
            onSwitchMode={e => setMode(+e.target.value)}
            onChangeFile={handleChangeFile}
        />
    );
}
